package com.mengtian_tech.tju.dataquery.api.util;

import java.lang.reflect.Field;
import java.util.Map;


public class MapToObjectUtil {
	  public static <T> T copyMapToObject(Map<String, Object> map, T target)  {
	        if (map == null || target == null) {
	            return target;
	        }
	        
	        Class<?> clazz = target.getClass();
	        
	        for (Map.Entry<String, Object> entry : map.entrySet()) {
	            String key = entry.getKey();
	            Object value = entry.getValue();
	            
	            try {
	                Field field = getField(clazz, key);
	                if (field != null) {
	                    field.setAccessible(true);
	                    // 转换值类型以匹配字段类型
	                    Object convertedValue = convertValue(value, field.getType());
	                    field.set(target, convertedValue);
	                }
	            } catch (NoSuchFieldException e) {
	                System.out.println("Warning: Target object has no field named '" + key + "'");
	            } catch (IllegalArgumentException e) {
	                System.out.println("Warning: Cannot convert value " ); 
	            } catch (IllegalAccessException e) {
					e.printStackTrace();
				}
	        }
	        
	        return target;
	    }
	    
	    private static Field getField(Class<?> clazz, String fieldName) throws NoSuchFieldException {
	        try {
	            return clazz.getDeclaredField(fieldName);
	        } catch (NoSuchFieldException e) {
	            Class<?> superClass = clazz.getSuperclass();
	            if (superClass != null) {
	                return getField(superClass, fieldName);
	            }
	            throw e;
	        }
	    }
	    
	    private static Object convertValue(Object value, Class<?> targetType) {
	        if (value == null) {
	            return null;
	        }
	        
	        // 如果类型已经匹配，直接返回
	        if (targetType.isInstance(value)) {
	            return value;
	        }
	        
	        // 处理字符串到其他基本类型的转换
	        if (value instanceof String) {
	            String strValue = (String) value;
	            if (targetType == Integer.class || targetType == int.class) {
	                return Integer.parseInt(strValue);
	            } else if (targetType == Long.class || targetType == long.class) {
	                return Long.parseLong(strValue);
	            } else if (targetType == Double.class || targetType == double.class) {
	                return Double.parseDouble(strValue);
	            } else if (targetType == Float.class || targetType == float.class) {
	                return Float.parseFloat(strValue);
	            } else if (targetType == Boolean.class || targetType == boolean.class) {
	                return Boolean.parseBoolean(strValue);
	            }
	        }
	        
	        // 可以添加更多类型转换逻辑
	        
	        // 如果无法转换，返回原始值，可能会在set时抛出异常
	        return value;
	    }
}
